#! /bin/sh
#
# Laptop mode tools module: control X display standby / suspend / off using DPMS
#

# getXuser gets the X user belonging to the display in $displaynum.
# (This code was borrowed from the Debian acpi-support package.)
getXuser() {
	user=`w -hs | awk '{ if ($3 == ":'$displaynum'" || $3 ~ /:'$displaynum'\..*/ || $2 == ":'$displaynum'" || $2 ~ /:'$displaynum'\..*/) { print $1; exit; } }'`
	if [ x"$user" = x"" ]; then
		startx=`pgrep -n startx`
		if [ x"$startx" != x"" ]; then
			user=`ps -o user --no-headers $startx`
		fi
	fi
	if [ x"$user" != x"" ]; then
        	userhome=`getent passwd $user | cut -d: -f6`
        	export XAUTHORITY=$userhome/.Xauthority
	else
		export XAUTHORITY=""
	fi
	export XUSER=$user
}


# Set X screen standby/suspend/powerdown timing
if [ x$CONTROL_DPMS_STANDBY = x1 ]  || [ x$ENABLE_AUTO_MODULES = x1 -a x$CONTROL_DPMS_STANDBY = xauto ]; then
	if [ $ON_AC -eq 1 ]; then
		if [ "$ACTIVATE" -eq 1 ]; then
			STANDBY="$LM_AC_DPMS_STANDBY"
			SUSPEND=$(($STANDBY+30))
			OFF=$(($STANDBY+60))
		else
			STANDBY="$NOLM_AC_DPMS_STANDBY"
			SUSPEND=$(($STANDBY+300))
			OFF=$(($STANDBY+600))
		fi
	else
		STANDBY="$BATT_DPMS_STANDBY"
		SUSPEND=$(($STANDBY+30))
		OFF=$(($STANDBY+60))
	fi

	# Loop through all X servers using their unix domain sockets.
	# (Partly borrowed from the Debian acpi-support package.)
	for x in /tmp/.X11-unix/*; do
		if [ -e "$x" ] ; then
			displaynum=`echo $x | sed -r 's#/tmp/.X11-unix/X([0-9]*)$#\1#'`
			log "VERBOSE" "Determining Xauthority for display $displaynum"
			getXuser;
			if [ x"$XAUTHORITY" != x"" ]; then
				export DISPLAY=":$displaynum"	    
				if su $XUSER -c "xset dpms $STANDBY $SUSPEND $OFF" 2>> $OUTPUT | grep -q display 2>&1 ; then
					log "VERBOSE" "Unable to set DPMS timeouts: X is not running on $DISPLAY"
				else 
					log "VERBOSE" "Set screen $DISPLAY for the user $XUSER to standby in $STANDBY s, suspend in $SUSPEND s, powerdown in $OFF s using Xauthority $XAUTHORITY"
				fi
			else
				log "VERBOSE" "Unable to determine Xauthority for display :$displaynum."
			fi
		fi
	done
else
	log "VERBOSE" "CONTROL_DPMS_STANDBY is disabled, skipping..."
fi

